package org.zhengquan.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zhengquan.common.Const;
import org.zhengquan.pojo.SysUser;
import org.zhengquan.service.SysUserService;
import org.zhengquan.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhengquan
 * @date 2017/10/31
 */
@Controller
@RequestMapping
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/login.page")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        SysUser sysUser = sysUserService.selectUserByKeyword(username);
        String errorMsg = "";
        String redirectPath = request.getParameter("redirectPath");
        if (StringUtils.isBlank(username)) {
            //用户名为空
            errorMsg = "用户名不能为空";
        } else if (StringUtils.isBlank(password)) {
            //密码为空
            errorMsg = "密码不能为空";
        } else if (sysUser == null) {
            //用户不存在
            errorMsg = "指定用户不存在";
        } else if (!sysUser.getPassword().equals(MD5Util.MD5EncodeUtf8(password))) {
            errorMsg = "用户名或密码错误";
        } else if (sysUser.getState() != 1) {
            errorMsg = "用户已被冻结,请联系管理员";
        } else {
            //登录成功
            request.getSession().setAttribute(Const.CURRENT_USER, sysUser);
            if (StringUtils.isNotBlank(redirectPath)) {
                response.sendRedirect(redirectPath);
            } else {
                response.sendRedirect("/admin/index.page");
            }
        }
        request.setAttribute("error", errorMsg);
        request.setAttribute("username", username);
        if (StringUtils.isNotBlank(redirectPath)) {
            request.setAttribute("redirectPath", redirectPath);
        }
        request.getRequestDispatcher(Const.SIGN_IN_PAGE).forward(request,response);
    }

    @RequestMapping("/logout.page")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        request.getRequestDispatcher(Const.SIGN_IN_PAGE).forward(request,response);
    }
}
